import json
import os
import re

r_opr_name = re.compile(r'(.*).txt')
r_name = re.compile(r'name = (.*)')
r_intro = re.compile(r'intro = (.*)')
r_pic = re.compile(r'pic_src = (.*)')


def handle_character():
    # 扫描目录
    obj = 'character'
    cla = 'Character'
    my_dir = './' + obj + '/'
    file_list = os.listdir(my_dir)
    out = open('./character-script.txt', mode='w', encoding='utf-8')
    for f in file_list:
        fin = open(my_dir + f, mode='r', encoding='utf-8')
        obj = {'opr_name': r_opr_name.findall(f)[0]}
        while True:
            fread = fin.readline()
            if not fread:
                break
            print(fread)
            name_list = r_name.findall(fread)
            obj['character_name'] = name_list[0]
            fread = fin.readline()
            obj['intro'] = r_intro.findall(fread)[0]
            fread = fin.readline()
            obj['pic_src'] = r_pic.findall(fread)[0]
            res_str = "db.session.add(" + cla + "(opr_name='"
            res_str += obj['opr_name'] + "', character_name='" + obj['character_name'] + "', intro='"
            res_str += obj['intro'] + "', pic_src='" + obj['pic_src'] + "'))\n"
            print(res_str)
            out.write(res_str)
    out.write("db.session.commit()\n")
    out.close()


if __name__ == "__main__":
    handle_character()
    pass
